package com.tree.thrive.global.utils.thread;

public class InheritableThreadLocalExample {

    private static final InheritableThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        // 在主线程中设置值
        threadLocal.set(1);

        Thread childThread = new Thread(() -> {
            // 在子线程中获取父线程的值，并加1后设置为自己的值
            int value = threadLocal.get();
            System.out.println("Child thread value 1 : " + value);
            threadLocal.set(value + 1);
            System.out.println("Child thread value 2 : " + threadLocal.get());
        });

        childThread.start();

        try {
            childThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 主线程中仍然可以获取之前设置的值
        System.out.println("Main thread value: " + threadLocal.get());
    }


}
